# _*_ coding:utf-8 _*_
# @Time  : 2023.08.02
# @Author: zizlee
from fastapi import APIRouter, Body, Query
from pydantic import BaseModel, validator
from db import FAConnection
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils

ruizhi_config_api = APIRouter()


class StrategyConfing(BaseModel):
    user_id: int = None
    variety_en: str = None
    expire_date: str

    @validator('expire_date')
    def validate_active_expire(cls, value):
        sd = datetime_utils.auth_datetime_string(value, f='%Y-%m-%d')
        if not sd:
            raise ValueError('expire_date invalidate! must be `yyyy-MM-dd`')
        return value


@ruizhi_config_api.post('/strategyConfig/')
def config_ruizhi_strategy(config: StrategyConfing = Body(...)):
    if not config.user_id and not config.variety_en:
        return AllResponse.validate_error(msg='参数错误')
    if config.user_id is None:
        exist_sql = "SELECT id FROM info_strategy_ruizhi_config WHERE variety_en=%s LIMIT 1;"
        exist_prm = [config.variety_en]
        config.user_id = 0
    else:
        exist_sql = "SELECT id FROM info_strategy_ruizhi_config WHERE user_id=%s LIMIT 1;"
        exist_prm = [config.user_id]
        config.variety_en = ''
    with FAConnection() as cursor:
        cursor.execute(exist_sql, exist_prm)
        exist = cursor.fetchone()
        if exist:
            cursor.execute("UPDATE info_strategy_ruizhi_config SET expire_date=%s WHERE id=%s LIMIT 1;",
                           [config.expire_date, exist['id']])
        else:
            print(config)
            cursor.execute("""
                INSERT INTO info_strategy_ruizhi_config (user_id,variety_en,expire_date) VALUES (%s,%s,%s);
            """, [config.user_id, config.variety_en, config.expire_date])
    return AllResponse.operate_successfully()


@ruizhi_config_api.get('/strategyConfig/')
def ruizhi_strategy_config(t: int = Query(..., ge=1, le=2)):
    if t == 1:  # 用户配置表
        sql = """
            SELECT a.id,a.user_id,a.expire_date,b.admin_name 
            FROM info_strategy_ruizhi_config As a 
            INNER JOIN ruizy_user As b ON a.user_id=b.id
            ORDER BY a.user_id;
        """
    elif t == 2:  # 品种配置表
        sql = """
            SELECT a.id,a.variety_en,a.expire_date,b.variety_name 
            FROM info_strategy_ruizhi_config As a 
            INNER JOIN ruizy_variety As b ON a.variety_en=b.variety_en
            ORDER BY a.variety_en;
        """
    else:
        return AllResponse.operate_successfully(data=[])
    with FAConnection() as cursor:
        cursor.execute(sql)
        ret_list = cursor.fetchall()
    return AllResponse.operate_successfully(data=ret_list)


@ruizhi_config_api.post('/investmentConfig/')
def config_ruizhi_strategy(config: StrategyConfing = Body(...)):
    if not config.user_id and not config.variety_en:
        return AllResponse.validate_error(msg='参数错误')
    if config.user_id is None:
        exist_sql = "SELECT id FROM exchange_plan_ruizhi_config WHERE variety_en=%s LIMIT 1;"
        exist_prm = [config.variety_en]
        config.user_id = 0
    else:
        exist_sql = "SELECT id FROM exchange_plan_ruizhi_config WHERE user_id=%s LIMIT 1;"
        exist_prm = [config.user_id]
        config.variety_en = ''
    with FAConnection() as cursor:
        cursor.execute(exist_sql, exist_prm)
        exist = cursor.fetchone()
        if exist:
            cursor.execute("UPDATE exchange_plan_ruizhi_config SET expire_date=%s WHERE id=%s LIMIT 1;",
                           [config.expire_date, exist['id']])
        else:
            cursor.execute("""
                INSERT INTO exchange_plan_ruizhi_config (user_id,variety_en,expire_date) VALUES (%s,%s,%s);
            """, [config.user_id, config.variety_en, config.expire_date])
    return AllResponse.operate_successfully()


@ruizhi_config_api.get('/investmentConfig/')
def ruizhi_strategy_config(t: int = Query(..., ge=1, le=2)):
    if t == 1:  # 用户配置表
        sql = """
            SELECT a.id,a.user_id,a.expire_date,b.admin_name 
            FROM exchange_plan_ruizhi_config As a 
            INNER JOIN ruizy_user As b ON a.user_id=b.id
            ORDER BY a.user_id;
        """
    elif t == 2:  # 品种配置表
        sql = """
            SELECT a.id,a.variety_en,a.expire_date,b.variety_name 
            FROM exchange_plan_ruizhi_config As a 
            INNER JOIN ruizy_variety As b ON a.variety_en=b.variety_en
            ORDER BY a.variety_en;
        """
    else:
        return AllResponse.operate_successfully(data=[])
    with FAConnection() as cursor:
        cursor.execute(sql)
        ret_list = cursor.fetchall()
    return AllResponse.operate_successfully(data=ret_list)
